<template>
  <div class="container">
    <div class="bill-detail" v-show="showDetail">
      <div class="weui_cells_title">就诊卡：</div>
      <div class="weui_cells weui_cells_access" style="margin-top:10px;">
        <a class="weui_cell" href="javascript:;">
          <div class="weui_cell_hd">
            <i class="fa fa-credit-card fa-2x icon-color" style="width:45px;margin-right:5px;display:block;"></i>
          </div>
          <div class="weui_cell_bd weui_cell_primary">
            <p>{{order.cardName}}</p>
            <p>{{order.cardNum}}</p>
          </div>
        </a>
      </div>
      <div class="weui_cells_title">缴费详情：</div>
      <div class="weui_cells">
        <!-- <div class="weui_cell">
          <div class="weui_cell_bd weui_cell_primary">
            <p>
              <span class="label">订&nbsp;&nbsp;单&nbsp;&nbsp;号</span>
              <span class="info">{{order.num}}</span>
            </p>
          </div>
        </div> -->
        <div class="weui_cell">
          <div class="weui_cell_bd weui_cell_primary">
            <p>
              <span class="label">总&nbsp;&nbsp;金&nbsp;&nbsp;额</span>
              <span class="info">{{selectedTotalAmt}} 元</span>
            </p>
          </div>
        </div>
        <div class="weui_cell" v-show="selectedSelfAmt">
            <div class="weui_cell_bd weui_cell_primary">
              <p>
                <span class="label">自费金额</span>
                <span class="info">{{selectedSelfAmt}} 元</span>
              </p>
            </div>
          </div>
          <div class="weui_cell" v-show="selectedSelfAmt">
            <div class="weui_cell_bd weui_cell_primary">
              <p>
                <span class="label">社保金额</span>
                <span class="info">{{selectedSbPayAmt}} 元</span>
              </p>
            </div>
          </div>
      </div>
      <a @click="doBill" href="javascript:;" style="margin:10px 8px;" class="weui_btn weui_btn_primary">确认缴费</a>
      <div>
        <p style="padding:10px;" class="am-ft-sm am-ft-gray">
          <span class="am-ft-orange"><i class="fa fa-info-circle"></i></span> 社保生育门诊、特定门诊病人请到收费处缴费结算，否则将全额自费。
        </p>
      </div>
      <div class="weui_cells_title">缴费明细：</div>
      <div class="weui_cells">
        <div v-for="item in items" class="weui_cell">
          <div class="weui_cell_bd weui_cell_primary">
            <p>
              <span style="display: block;">处方单号：<span style="color: #0ae;">{{item.recipeId}}</span></span>
              <span style="display: block;">科室：<span style="color: #0ae;">{{item.deptName}}</span></span>
              <span style="display: block;">医生：<span style="color: #0ae;">{{item.docName}}</span></span>
              <span style="display: block;">就诊时间：<span style="color: #0ae;">{{item.cureDate}}</span></span>
              <span style="display: block;">费用类别：<span style="color: #0ae;">{{item.payType}}</span></span>
              <span style="display: block;">处方类型：<span style="color: #0ae;">{{item.recipeType}}</span></span>
              <span style="display: block;">缴费总金额：<span style="color: #0ae;">{{item.totalAmt}} 元</span></span>
              <span style="display: block;" v-show="item.selfAmt">自费金额：<span style="color: #0ae;">{{item.selfAmt}} 元</span></span>
              <span style="display: block;" v-show="item.sbPayAmt">社保金额：<span style="color: #0ae;">{{item.sbPayAmt}} 元</span></span>
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="bill-success" v-show="showSuccess">
      <div class="weui_msg">
        <div class="weui_icon_area"><i class="weui_icon_success weui_icon_msg"></i></div>
        <div class="weui_text_area">
          <h2 class="weui_msg_title">缴费成功</h2>
          <p class="weui_msg_desc">{{succeedMsg}}</p>
        </div>
        <div class="weui_opr_area">
          <p class="weui_btn_area">
            <a href="javascript:;" @click="goOrderDetail" class="weui_btn weui_btn_primary">查看详情</a>
          </p>
        </div>
      </div>
    </div>
    <div class="bill-failed" v-show="showFailed">
      <div class="weui_msg">
        <div class="weui_icon_area"><i class="weui_icon_warn weui_icon_msg"></i></div>
        <div class="weui_text_area">
          <h2 class="weui_msg_title">缴费失败</h2>
          <p class="weui_msg_desc">{{failedMsg}}</p>
        </div>
        <div class="weui_opr_area">
          <p class="weui_btn_area">
            <a href="javascript:;" @click="gotoPortal" class="weui_btn weui_btn_primary">返回首页</a>
          </p>
        </div>
      </div>
    </div>
    <partial name="footer-copyright"></partial>
  </div>
</template>
<style>
.weui_msg_desc label {
  width: 80px;
  display: inline-block;
}

.weui_msg_desc span {
  color: #0ae;
  font-weight: bolder;
}

span.label {
  display: inline-block;
  width: 80px;
}

span.info {
  color: #0ae;
}

.blue_tag {
  background-color: #0ae;
  color: #fff;
  font-size: 13px;
  padding: 2px 4px;
  border: none;
  vertical-align: middle;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
}
</style>
<script>
/*global WeixinJSBridge*/

import {
  setBillOrderNum,
  showCommonToast,
  hideCommonToast,
  showLoadingToast,
  hideLoadingToast
} from '../../vuex/actions'

import _ from 'underscore'

export default {
  name: 'DoBillView',
  data: function () {
    return {
      showDetail: true,
      showSuccess: false,
      showFailed: false,
      failedMsg: '',
      succeedMsg: '',
      isPaySucceed: false,
      selectedRecipeIds: this.$route.query.selectedRecipeIds,
      selectedTotalAmt: '',
      selectedSelfAmt: '',
      selectedSbPayAmt: '',
      items: []
    }
  },
  methods: {
    doBill: function () {
      if (this.order.id === -1) {
        return
      }
      var self = this

      this.showLoadingToast({ msg: '正在缴费...' }, false)
      this.$ajax.get('PayBill', 'Bill', {
        orderId: this.order.id
      }, false).then(function (data) {
        if (data.ResultCode !== '0') {
          self.failedMsg = data.ResultMsg
          self.showDetail = false
          self.showSuccess = false
          self.showFailed = true
          self.hideLoadingToast()
        } else {
          self.callPay(data.PayString)
        }
      })
    },
    gotoPortal: function () {
      this.$router.replace({ name: 'portal' })
    },
    goOrderDetail: function () {
      this.$router.replace({ name: 'billOrderDetail', params: { orderId: this.order.id } })
    },
    callPay: function (payString) {
      if (payString === '') {
        this.paySucceed()
        return
      }
      var self = this
      WeixinJSBridge.invoke('getBrandWCPayRequest', JSON.parse(payString), function (res) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        // 因此微信团队建议，当收到ok返回时，向商户后台询问是否收到交易成功的通知，若收到通知，前端展示交易成功的界面；
        // 若此时未收到通知，商户后台主动调用查询订单接口，查询订单的当前状态，并反馈给前端展示相应的界面。
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          self.paySucceed()
        } else {
          self.payFailed()
        }
      })
    },
    payFailed: function () {
      this.cancelPay()
      this.hideLoadingToast()

      this.showCommonToast({ msg: '您已取消缴费' })
      window.history.go(-1)
    },
    paySucceed: function () {
      this.isPaySucceed = true

      var self = this
      this.$ajax.get('GetBillStatus', 'Bill', {
        orderId: this.order.id
      }, false).then(function (data) {
        if (data.ResultCode !== '0') {
          self.hideLoadingToast()
          window.history.go(-1)
        } else {
          if (data.BillStatus === '1') {
            self.failedMsg = data.FailedMsg
            self.showDetail = false
            self.showSuccess = false
            self.showFailed = true
            self.hideLoadingToast()
          } else if (data.BillStatus === '0') {
            self.showDetail = false
            self.showSuccess = true
            self.showFailed = false
            self.succeedMsg = data.ResultMsg
            self.hideLoadingToast()
          } else {
            window.setTimeout(function () {
              self.paySucceed()
            }, 500)
          }
        }
      })
    },
    cancelPay: function () {
      if (this.order.id !== -1 && !this.isPaySucceed) {
        this.$ajax.get('PayFailed', 'Bill', {
          orderId: this.order.id
        }, false).then(function (data) {

        })
      }
    }
  },
  vuex: {
    getters: {
      order: ({ billOrder }) => billOrder
    },
    actions: {
      setBillOrderNum,
      showCommonToast,
      hideCommonToast,
      showLoadingToast,
      hideLoadingToast
    }
  },
  ready: function () {
    var self = this
    this.$ajax.get('CreateBillOrder', 'Bill', {
      cardId: this.order.cardId,
      selectedRecipeIds: this.selectedRecipeIds
    }).then(function (data) {
      if (data.ResultCode !== '0') {
        self.failedMsg = data.ResultMsg
        self.showDetail = false
        self.showSuccess = false
        self.showFailed = true
      } else {
        self.setBillOrderNum(data.OrderId, data.OrderNo)

        self.selectedTotalAmt = data.SelectedTotalAmt
        self.selectedSelfAmt = data.SelectedSelfAmt
        self.selectedSbPayAmt = data.SelectedSbPayAmt

        self.items = _.map(data.ClinRecipeOrderItems, function (val) {
          return {
            recipeId: val.RecipeId,
            deptName: val.DeptName,
            docName: val.DocName,
            cureDate: val.CureDate,
            payType: val.PayType,
            recipeType: val.RecipeType,
            totalAmt: val.TotalAmt,
            selfAmt: val.SelfAmt,
            sbPayAmt: val.SbPayAmt
          }
        })
      }
    })
  },
  route: {
    activate: function (transition) {
      // 阻止页面刷新，刷新时直接跳往首页
      if (transition.from.name === undefined && !this.$route.query.clinicNo) {
        this.$router.go({ name: 'portal' })
      } else {
        transition.next()
      }
    },
    deactivate: function (transition) {
      this.cancelPay()
      this.setBillOrderNum(-1, '')
      transition.next()
    }
  }
}
</script>
